package com.xuxueli.applyModules.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 说明：常用工具
 * 修改时间：2015年11月24日
 * @version
 */
public class Tools {

    /**
     * 随机生成六位数验证码
     * @return
     */
    public static int getRandomNum(){
        Random r = new Random();
        return r.nextInt(900000)+100000;//(Math.random()*(999999-100000)+100000)
    }

    /**
     * 检测字符串是否不为空(null,"","null")
     * @param s
     * @return 不为空则返回true，否则返回false
     */
    public static boolean notEmpty(String s){
        return s!=null && !"".equals(s) && !"null".equals(s);
    }

    /**
     * 检测字符串是否为空(null,"","null")
     * @param s
     * @return 为空则返回true，不否则返回false
     */
    public static boolean isEmpty(String s){
        return s==null || "".equals(s) || "null".equals(s);
    }

    /**
     * 字符串转换为字符串数组
     * @param str 字符串
     * @param splitRegex 分隔符
     * @return
     */
    public static String[] str2StrArray(String str,String splitRegex){
        if(isEmpty(str)){
            return null;
        }
        return str.split(splitRegex);
    }

    /**
     * 用默认的分隔符(,)将字符串转换为字符串数组
     * @param str	字符串
     * @return
     */
    public static String[] str2StrArray(String str){
        return str2StrArray(str,",\\s*");
    }

    /**
     * 按照yyyy-MM-dd HH:mm:ss的格式，日期转字符串
     * @param date
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String date2Str(Date date){
        return date2Str(date,"yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 按照yyyy-MM-dd HH:mm:ss的格式，字符串转日期
     * @param date
     * @return
     */
    public static Date str2Date(String date){
        if(notEmpty(date)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                return sdf.parse(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return new Date();
        }else{
            return null;
        }
    }

    /**
     * 按照参数format的格式，日期转字符串
     * @param date
     * @param format
     * @return
     */
    public static String date2Str(Date date,String format){
        if(date!=null){
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.format(date);
        }else{
            return "";
        }
    }

    /**
     * 把时间根据时、分、秒转换为时间段
     * @param StrDate
     */
    public static String getTimes(String StrDate){
        String resultTimes = "";

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now;

        try {
            now = new Date();
            Date date=df.parse(StrDate);
            long times = now.getTime()-date.getTime();
            long day  =  times/(24*60*60*1000);
            long hour = (times/(60*60*1000)-day*24);
            long min  = ((times/(60*1000))-day*24*60-hour*60);
            long sec  = (times/1000-day*24*60*60-hour*60*60-min*60);

            StringBuffer sb = new StringBuffer();
            //sb.append("发表于：");
            if(hour>0 ){
                sb.append(hour+"小时前");
            } else if(min>0){
                sb.append(min+"分钟前");
            } else{
                sb.append(sec+"秒前");
            }

            resultTimes = sb.toString();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return resultTimes;
    }

    /**
     * 写txt里的单行内容
     * @param content  写入的内容
     */
    public static void writeFile(String fileP,String content){
        String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"../../";	//项目路径
        filePath = (filePath.trim() + fileP.trim()).substring(6).trim();
        if(filePath.indexOf(":") != 1){
            filePath = File.separator + filePath;
        }
        try {
            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(filePath),"utf-8");
            BufferedWriter writer=new BufferedWriter(write);
            writer.write(content);
            writer.close();


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 验证邮箱
     * @param email
     * @return
     */
    public static boolean checkEmail(String email){
        boolean flag = false;
        try{
            String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            flag = matcher.matches();
        }catch(Exception e){
            flag = false;
        }
        return flag;
    }

    /**
     * 验证手机号码
     * @return
     */
    public static boolean checkMobileNumber(String mobileNumber){
        boolean flag = false;
        try{
            Pattern regex = Pattern.compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$");
            Matcher matcher = regex.matcher(mobileNumber);
            flag = matcher.matches();
        }catch(Exception e){
            flag = false;
        }
        return flag;
    }

    /**
     * 检测KEY是否正确
     * @param paraname  传入参数
     * @param FKEY		接收的 KEY
     * @return 为空则返回true，不否则返回false
     */
    public static boolean checkKey(String paraname, String FKEY){
        paraname = (null == paraname)? "":paraname;
        return MD5.md5(paraname+DateUtils.getDays()+",fh,").equals(FKEY);
    }

    /**
     * 读取txt里的单行内容
     */
    public static String readTxtFile(String fileP) {
        try {

            String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"../../";	//项目路径
            filePath = filePath.replaceAll("file:/", "");
            filePath = filePath.replaceAll("%20", " ");
            filePath = filePath.trim() + fileP.trim();
            if(filePath.indexOf(":") != 1){
                filePath = File.separator + filePath;
            }
            String encoding = "utf-8";
            File file = new File(filePath);
            if (file.isFile() && file.exists()) { 		// 判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file), encoding);	// 考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    return lineTxt;
                }
                read.close();
            }else{
                System.out.println("找不到指定的文件,查看此路径是否正确:"+filePath);
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
        }
        return "";
    }

    public static void setRespJsonIntoRequest(Object obj) {
        getCurrentRequest().setAttribute("responseJson", obj);
    }

    public static HttpServletRequest getCurrentRequest() {
        return ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
    }

    //身份证
    public static boolean isIdCard(String idCardString)
    {
        String idCardPattern = "^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
        return Pattern.matches(idCardPattern, idCardString);
    }

    //手机
    public static boolean isMobile(String mobileString){
        String mobilePattern = "^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$";
        return Pattern.matches(mobilePattern, mobileString);
    }

    public static String convertStrToBase64(String str){
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(str.getBytes());
    }

    public static String convertBase64ToStr(String str){
        try{
            BASE64Decoder decoder = new BASE64Decoder();
            return new String(decoder.decodeBuffer(str));
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //遍历指定路径下的各个txt文本
    public static List<String> getFileList(File file) {
        List<String> result = new ArrayList<String>();
        if (!file.isDirectory()) {
            System.out.println(file.getAbsolutePath());
            result.add(file.getAbsolutePath());
        } else {
            File[] directoryList = file.listFiles(new FileFilter() {
                public boolean accept(File file) {
                    if (file.isFile() && file.getName().indexOf("txt") > -1) {
                        return true;
                    } else {
                        return false;
                    }
                }
            });
            for (int i = 0; i < directoryList.length; i++) {
                result.add(directoryList[i].getPath());
            }
        }
        return result;
    }

    //转换成拼音
    public static String getPinYin(String src) {
        char[] t1 = null;
        t1 = src.toCharArray();
        String[] t2 = new String[t1.length];
        HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
        t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        t3.setVCharType(HanyuPinyinVCharType.WITH_V);
        String t4 = "";
        int t0 = t1.length;
        try {
            for (int i = 0; i < t0; i++) {
                // System.out.println(t1[i]);
                if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
                    t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);
                    t4 += t2[0];
                } else {
                    t4 += Character.toString(t1[i]);
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }
        return t4;
    }

    //汉字转换成拼音的首字母
    public static String getPinYinHeadChar(String str) {
        String convert = "";
        for (int j = 0; j < str.length(); j++) {
            char word = str.charAt(j);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += pinyinArray[0].charAt(0);
            } else {
                convert += word;
            }
        }
        return convert;
    }

    //读取mai_config一个参数值
    public static String getStringFromEnvconfig(String name) {
        ResourceBundle resourceBundle = ResourceBundle.getBundle("mail_config");
        return resourceBundle.getString(name);
    }
    public static String getCnASCII(String cnStr) {
        StringBuffer strBuf = new StringBuffer();
        byte[] bGBK = cnStr.getBytes();
        for (int i = 0; i < bGBK.length; i++) {
            strBuf.append(Integer.toHexString(bGBK[i] & 0xff) + " ");
        }
        return strBuf.toString();
    }

    //随机产生6位数字
    public static String getRandomSixNum() {
        String strs = "";
        for (int i = 0; i < 6; i++) {
            Random random = new Random();
            String str = String.valueOf(random.nextInt(10));
            strs += str;
        }
        return strs;
    }

    //加密处理
    public static String string2MD5(String inStr) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();

    }

    public static String formatDate(Date date){
        return formatDate(date,"yyyy-MM-dd HH:mm:ss");
    }

    public static String formatDate(Date date, String pattern){
        SimpleDateFormat dateFormat=new SimpleDateFormat(pattern);
        return dateFormat.format(date);
    }

    public static Date parseDate(String dateString) throws ParseException{
        return parseDate(dateString,"yyyy-MM-dd HH:mm:ss");
    }

    public static Date parseDate(String dateString, String pattern) throws ParseException{
        SimpleDateFormat dateFormat=new SimpleDateFormat(pattern);
        return dateFormat.parse(dateString);
    }

    public static String convertCountry(String countryId){
        return countryId==Const.COUNTRY_CHINA?"中国":"其他";
    }

    public static String convertBloodType(String bloodType){
        if(bloodType.equals("A")){
            return Const.BLOOD_TYPE_A;
        }else if(bloodType.equals("B")){
            return Const.BLOOD_TYPE_B;
        }else if(bloodType.equals("C")){
            return Const.BLOOD_TYPE_AB;
        }else {
            return Const.BLOOD_TYPE_O;
        }
    }

    //文件后缀名
    public static String getFileSuffix(String fullName) {
        return fullName.substring(fullName.lastIndexOf("."));
    }

    //判断图片的格式
    public static boolean isPic(File file) {
        String suffix=Tools.getFileSuffix(file.getName());
        if (suffix.equalsIgnoreCase(".png")) {
            return true;
        } else {
            return false;
        }
    }

    //当前日期减1
    public static String beforeDate(){
        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        String date = "";
        int dayval = 0;
        if (day!=1) {
            dayval = day+(-1);
            String monthval = "";
            if (month<10) {
                monthval = "0"+String.valueOf(month);
            }else{
                monthval = String.valueOf(month);
            }
            String dayvalue = "";
            if (dayval<10) {
                dayvalue = "0"+String.valueOf(dayval);
            }else{
                dayvalue = String.valueOf(dayval);
            }
            date = String.valueOf(year)+"-"+monthval+"-"+dayvalue;
        }else{
            month = month + (-1);
            dayval = getMaxDays(year,month);
            String monthval = "";
            if (month<10) {
                monthval = "0"+String.valueOf(month);
            }else{
                monthval = String.valueOf(month);
            }
            String dayvalue = "";
            if (dayval<10) {
                dayvalue = "0"+String.valueOf(dayval);
            }else{
                dayvalue = String.valueOf(dayval);
            }
            date = String.valueOf(year)+"-"+monthval+"-"+dayvalue;
        }
        return date;
    }

    public static int getMaxDays(int year,int month){
        int days = -1;
        switch (month) {
            case 4:
            case 6:
            case 9:
            case 11:
                days = 30;
                break;
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                days = 31;
                break;
            case 2:
                //判断该年是否闰年
                if(isLeapYear(year)){//是闰年
                    days = 29;
                }else{
                    days = 28;
                }
                break;
            default:
                System.out.println("对不起,您的输入不合法!");
                break;
        }
        return days;
    }
    /**
     * 判断某年是否为闰年
     */
    public static boolean isLeapYear(int year){
        //内置的判断闰年的方法
        if((year%4==0 && year%100!=0)||year%400==0){
            return true;
        }
        return false;
    }
    public static void excel2(HttpServletRequest request,HttpServletResponse response)throws Exception{
        WritableWorkbook wwb = null;
        OutputStream ops = null;
        InputStream fis = null;
        String path = null;
        Integer count = 0;
        PageTools page = new PageTools();
        PageData pd = new PageData();
        page.setPd(pd);
        String customer = pd.getString("customer");
        if(null != customer && !"".equals(customer)){
            pd.put("customer", customer.trim());
        }
        String jobCode = pd.getString("jobCode");
        if(null != jobCode && !"".equals(jobCode)){
            pd.put("jobCode", jobCode.trim());
        }
        String contractNo = pd.getString("contractNo");
        if(null != contractNo && !"".equals(contractNo)){
            pd.put("contractNo", contractNo.trim());
        }
        String flags = pd.getString("flag");
        if(null != flags && !"".equals(flags)){
            pd.put("flags", flags.trim());
        }
        try{
            List<PageData> varOList = new ArrayList<>();
            path = "D:\\"+"项目计划(电脑版).xls";
            File file=new File(path);
            if (!file.exists()) {
                file.createNewFile();
            }
            wwb = Workbook.createWorkbook(file);
            WritableSheet ws = wwb.createSheet("项目计划(电脑版)",0);
            //给sheet电子版中所有的列设置默认的列的宽度;
            ws.getSettings().setDefaultColumnWidth(15);
            ws.mergeCells(0,count,6,0);
            jxl.write.WritableFont wfont = new  jxl.write.WritableFont(WritableFont.createFont("宋体"),14,WritableFont.BOLD,false);
            wfont.setColour(Colour.BLACK);
            WritableCellFormat wc = new WritableCellFormat(wfont);
            wc.setAlignment(Alignment.CENTRE);
            wc.setBorder(Border.ALL, BorderLineStyle.DOUBLE);
            Label labelTitle = new Label(0, count, "项目计划表", wc);
            Label labeljlh = new Label(0, count+1, "客户", wc);
            Label labelzzbh = new Label(1, count+1, "订单编号", wc);
            Label labelcpmc = new Label(2, count+1, "制造编号", wc);
            Label labelsfks = new Label(3, count+1, "客户交期", wc);
            Label labelzpzt = new Label(4, count+1, "起始日期", wc);
            Label labeljhlx = new Label(5, count+1, "首试日期", wc);
            Label labelddyxd = new Label(6, count+1, "进度率%", wc);
            count++;

            ws.addCell(labelTitle);
            ws.addCell(labeljlh);
            ws.addCell(labelzzbh);
            ws.addCell(labelcpmc);
            ws.addCell(labelsfks);
            ws.addCell(labelzpzt);
            ws.addCell(labeljhlx);
            ws.addCell(labelddyxd);
            for (int i = 0; i < varOList.size(); i++) {
                Integer sfks = varOList.get(i).getInteger("CUSTOMER_CODE");
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Date job_date = varOList.get(i).getDate("JOB_DELIVERY");
                Date start_date = varOList.get(i).getDate("JOB_START_DATE");
                Date trial_date = varOList.get(i).getDate("JOB_TRIAL_DATE");
                String job_datestr ="";
                if(job_date!=null){
                    job_datestr = format.format(job_date);
                }
                String start_datestr ="";
                if(start_date!=null){
                    start_datestr = format.format(start_date);
                }
                Calendar now3 = Calendar.getInstance();
                String trial_datestr ="";
                int trialYear=2000;
                if(trial_date!=null){
                    now3.setTime(trial_date);
                    int sch_year = now3.get(Calendar.YEAR);
                    if (sch_year<trialYear) {
                        trial_datestr="";
                    }else{
                        trial_datestr = format.format(trial_date);
                    }
                }else{
                    trial_datestr="";
                }
                BigDecimal process1 = varOList.get(i).getBigDecimal("JOB_PROGRESS");
                BigDecimal process2 = new BigDecimal(100);
                Double value = process1.multiply(process2).doubleValue();
                DecimalFormat df = new DecimalFormat("#.0");
                String process_value = df.format(value).toString();
                if (process_value.equals("100.0")) {
                    process_value = process_value.substring(0, process_value.lastIndexOf("."));
                }
                Label labelcustomer_i= new Label(0, count+1, sfks.toString());
                Label labelcontract_i= new Label(1, count+1, varOList.get(i).getString("CONTRACT_NO"));
                Label labelcode_i= new Label(2, count+1, varOList.get(i).getString("JOB_CODE"));
                Label labeljob_i= new Label(3, count+1, job_datestr);
                Label labeljobdate_i= new Label(4, count+1, start_datestr);
                Label labeltrial_date_i= new Label(5, count+1, trial_datestr);
                Label labelprocess_i= new Label(6, count+1, value<1.00?"":process_value+"%");

                ws.addCell(labelcustomer_i);
                ws.addCell(labelcontract_i);
                ws.addCell(labelcode_i);
                ws.addCell(labeljob_i);
                ws.addCell(labeljobdate_i);
                ws.addCell(labeltrial_date_i);
                ws.addCell(labelprocess_i);
                count++;

                String JOB_REC_ID = varOList.get(i).getString("VIEWJOB_ID");
                PageData pds = new PageData();
                if(null != JOB_REC_ID && !"".equals(JOB_REC_ID)){
                    pds.put("JOB_REC_ID", JOB_REC_ID.trim());
                }
                List<ViewJobItems> var0List = new ArrayList<>();
                Calendar now1 = Calendar.getInstance();
                Calendar now2 = Calendar.getInstance();
                if(var0List.size()>0){
                    Label lablecode= new Label(1, count+1, "项目节点");
                    Label lableMerchantName= new Label(2, count+1, "周期");
                    Label labelDisTributeAmount= new Label(3, count+1, "预定完成日");
                    Label labelDisTributeCreateTime= new Label(4, count+1, "实际完成日");
                    count++;

                    ws.addCell(lablecode);
                    ws.addCell(lableMerchantName);
                    ws.addCell(labelDisTributeAmount);
                    ws.addCell(labelDisTributeCreateTime);
                    for (ViewJobItems viewJobItems : var0List) {
                        String code = viewJobItems.getCODE();
                        String name = viewJobItems.getNAME();
                        Double dates = viewJobItems.getSCH_DAYS();
                        Date SCH_FINISH_DATE = viewJobItems.getSCH_FINISH_DATE();
                        int comparerYear=2000;
                        String sch_datestr ="";
                        if(SCH_FINISH_DATE!=null){
                            now1.setTime(SCH_FINISH_DATE);
                            int sch_year = now1.get(Calendar.YEAR);
                            if (sch_year<comparerYear) {
                                sch_datestr="";
                            }else{
                                sch_datestr = format.format(SCH_FINISH_DATE);
                            }
                        }else{
                            sch_datestr="";
                        }
                        Date ACT_FINISH_DATE = viewJobItems.getACT_FINISH_DATE();
                        String act_datestr ="";
                        if(ACT_FINISH_DATE!=null){
                            now2.setTime(ACT_FINISH_DATE);
                            int act_year = now2.get(Calendar.YEAR);
                            if (act_year<comparerYear) {
                                act_datestr="";
                            }else{
                                act_datestr = format.format(ACT_FINISH_DATE);
                            }
                        }else{
                            act_datestr="";
                        }
                        Label labelMerchantName_i= new Label(1, count+1, code+" "+name);
                        Label labelDisTributeAmount_i= new Label(2, count+1, dates.toString());
                        Label labelDisTributeCreateTime_i= new Label(3, count+1, sch_datestr);
                        Label labelDistributeStatus_i= new Label(4, count+1, act_datestr);
                        ws.addCell(labelMerchantName_i);
                        ws.addCell(labelDisTributeAmount_i);
                        ws.addCell(labelDisTributeCreateTime_i);
                        ws.addCell(labelDistributeStatus_i);
                        count++;
                    }
                }
            }

            wwb.write();
            wwb.close();
            fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=项目计划(电脑版).xls");
            response.addHeader("Content-Length", "" + file.length());
            ops = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            ops.write(buffer);
            ops.flush();

        } catch(Exception e) {
            e.printStackTrace();
        } finally{
            try{
                if( fis != null){
                    fis.close();
                }
                if( ops != null){
                    ops.close();
                }
            }catch (Exception e1) {
                e1.printStackTrace();
            }
            if(path != null){
                boolean flag = deleteFile(path);
            }
        }
    }

    public static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    public static void main(String[] args) throws IOException {
        System.out.println(getPinYin("你好"));
        System.out.println(getRandomNum());
        System.out.println("**********************");
        //读取指定文件下各个txt文本里的内容
		/*String encoding="GBK";
		String dfs = FileUpload.getTXTFile();
	  	File filesd = new File(dfs);
	  	 List<String> result = new ArrayList<String>();
	  	result = getFileList(filesd);
		//File[] files=filesd.listFiles();
	  	for (String string : result) {
				InputStreamReader read = new InputStreamReader(new FileInputStream(string),encoding);//考虑到编码格式
	            BufferedReader br = new BufferedReader(read);
	            //String filename = string.getName();
				String line=null;
				while((line = br.readLine())!=null){
					line = line.replaceAll(" +", ",");
					if (line.equals(",")) {
						break;
					}else{
					String[] arr = line.split(",");
					//System.out.println("这是第"+filename.substring(0, 1)+"号机床的电流检测");
					System.out.println("电流检测时间:"+"20"+arr[0].replace("/", "-")+" "+arr[1]);
					System.out.println("a电流的值:"+arr[2]);
					System.out.println("b电流的值:"+arr[3]);
					System.out.println("c电流的值:"+arr[4]);
					System.out.println("三相电流的最大电流的值:"+arr[5]);
					System.out.println("机床的状态:"+arr[6]);
					System.out.println("机床状态的名称:"+arr[7]);
					System.out.println("停机时间:"+arr[8]);
					System.out.println("待机时间:"+arr[9]);
					System.out.println("加工时间:"+arr[10]);
					System.out.println("*****#####********");
					}
				}
	     }*/
        System.out.println(getPinYinHeadChar("你好"));
        System.out.println(getCnASCII("你好"));
        System.out.println(getRandomSixNum());
        System.out.println(string2MD5("1"));
        String ddluwj = "1-2017-10-1.txt";
        File file = new File(ddluwj);
        String filename = file.getName();
        filename = filename.replace("-", ",");
        String[] file_name = filename.split(",");
        String ds = file_name[0];
        String ds1 = file_name[1];
        String ds2 = file_name[2];
        int mont = Integer.parseInt(ds2);
        String dsa = null;
        if (mont<10) {
            dsa = "0"+String.valueOf(mont);
        }else{
            dsa = String.valueOf(mont);
        }
        String ds3 = file_name[3];
        ds3 = ds3.substring(0, ds3.lastIndexOf("."));
        int day = Integer.parseInt(ds3);
        String dsas = null;
        if (day<10) {
            dsas = "0"+String.valueOf(day);
        }else{
            dsas = String.valueOf(day);
        }
        System.out.println(ds);
        System.out.println(ds1);
        System.out.println(dsa);
        System.out.println(dsas);
        System.out.println(beforeDate());
        HttpServletRequest request = null;
        HttpServletResponse response = null;
        try {
            excel2(request,response);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }



}